package com.tanhua.dubbo.api;

import com.tanhua.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;


/**
 * @author wjs
 * @version 1.0
 * @date 2021/12/29 0029 下午 5:09
 */

@DubboService
public class FriendApiImpl implements FriendApi{

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void save(Long userId, Long friendId) {
        //保存userId好友friendId
        saveFriend(userId, friendId);
        //保存friendId好友userId
        saveFriend(friendId,userId);
    }

    @Override
    public List<Friend> findPage(Long userId, Integer page, Integer pagesize) {
        Query query = Query.query(Criteria.where("userId").is(userId))
                .skip((page-1)*pagesize)
                .limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));

        return mongoTemplate.find(query,Friend.class);
    }

    /**
     * 保存用户好友关系
     * @param userId 当前用户id
     * @param friendId 当前用户好友id
     */
    private void saveFriend(Long userId, Long friendId) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("frinedId").is(friendId));
        //判断好友关系是否存在
        if (!mongoTemplate.exists(query, Friend.class)) {
            //如果不存在，保存
            Friend friend1 = new Friend();
            friend1.setUserId(userId);
            friend1.setFriendId(friendId);
            friend1.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend1);
        }
    }
}
